/**
 * 步可以拖动的一个上传文件列表，留在这里备用
 */
import React from 'react';
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getBase64 } from '@/utils/img';

import type { UploadChangeParam } from 'antd/lib/upload';
import type { UploadFile } from 'antd/lib/upload/interface';
import { getToken } from '@/services/tokenInfo';

export default () => {
  const [fileList, setFileList] = React.useState<UploadFile<any>[]>([
    {
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      // url: '/imgs/shop/common/2021-08-02-10:12:43717016464.png',
    },
    {
      uid: '-2',
      name: 'image.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
      // url: '/imgs/shop/common/2021-08-02-10:12:462031513574.png',
    },
  ]);

  const [previewInfo, setPreviewInfo] = React.useState({
    title: '',
    src: '',
  });

  const [previewVisible, setPreviewVisible] = React.useState(false);

  const handlePreview = async (file: any) => {
    let preview;
    if (!file.url && !file.preview) {
      preview = await getBase64(file.originFileObj);
    }
    setPreviewVisible(true);
    setPreviewInfo({
      title: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
      src: file.url || preview,
    });
  };

  /**
   * 图片列表中的内容发生变化时，触发这个事件
   * @param info
   */
  const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'done') {
      console.log(info);
      console.log(info.file.response);
    }
    // 将最终的图片信息info.fileList，设置到fileList中。
    setFileList(info.fileList);
  };

  // 上传的图片控件
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <>
      <Upload
        action="/api/admin/upload/temp"
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
        headers={{ Authorization: getToken() as string }}
      >
        {fileList.length >= 8 ? null : uploadButton}
      </Upload>
      <Modal
        visible={previewVisible}
        title={previewInfo.title}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="example" style={{ width: '100%' }} src={previewInfo.src} />
      </Modal>
    </>
  );
};
